// 两根线
// 同步：组件 commit -> mutations -> state
// 异步： 组件 dispatch -> actions -> commit -> mutations -> state
import axios from 'axios'
export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: {
    list: []
  },
  // 相当于组件中计算属性
  getters: {
    total(state) {
      return state.list.reduce((p, c) => p + c.count, 0)
    },
    totalPrice(state) {
      return state.list.reduce((p, c) => p + c.count * c.price, 0)
    }
  },
  // 这个是唯一修改state中数据地方
  mutations: {
    // setCount(state) {}
    setCart(state, payload) {
      state.list = payload
    },
    updateCount(state, payload) {
      const obj = state.list.find((item) => item.id === payload.id)
      obj.count = payload.count
    }
  },
  // 写异步的ajax的地方
  actions: {
    // store.commit()
    // getData(store){}
    async getCart(context) {
      const { data } = await axios({
        url: 'http://127.0.0.1:9999/cart'
      })
      context.commit('setCart', data)
    },
    async changeCount(context, payload) {
      await axios({
        method: 'patch',
        url: `http://127.0.0.1:9999/cart/${payload.id}`,
        data: { count: payload.count }
      })
      context.commit('updateCount', payload)
    }
  }
}
